<template>
    <van-popup v-model:show="show"
               @close="$emit('close')"
               position="left"
               :style="{ width: '75%', height: '100%' }">
        <!-- 导航栏 -->
        <van-row>
            <van-nav-bar ref="refTopBaiHeight" title="会话列表" :style="{width: '100%'}">
                <template #left>
                    <van-button size="mini" plain hairline type="warning">
                        <van-icon @click='handleRemoveChatAll' name="delete-o" style="color: var(--van-warning-color)">
                            全部删除
                        </van-icon>
                    </van-button>
                </template>
                <template #right>
                    <van-icon @click="show = false" name="arrow-left" color="var(--van-text-color)" size="18"/>
                </template>
            </van-nav-bar>
        </van-row>

        <!-- 会话列表 -->
        <van-row>
            <van-list style="width: 100%"
                      :immediate-check="listData.immediateCheck"
                      v-model:loading="listData.loading"
                      v-model:error="listData.error"
                      :finished="listData.finished"
                      @load="handleListChat">
                <van-cell-group>
                    <span v-for="e in listData.list" :key="e.id" :title="e.title">
                        <!-- 修改中 -->
                        <van-cell v-if="e.editing"
                                  clickable
                                  icon='chat-o'>
                            <template #title>
                                <van-field ref="editChatInputDom"
                                           style="padding: 0; border: 1px solid white; border-radius: 1vw"
                                           v-model="chatData.title"
                                           placeholder="请输入标题"
                                           maxlength="10"/>
                            </template>

                            <template #extra>
                                <van-button @click.stop="handleEditChat"
                                            size="mini"
                                            color="linear-gradient(to right, #ff6034, #ee0a24)"
                                            style="margin-left: 2vw">
                                    完成
                                </van-button>
                                <van-icon @click.stop='handleRemoveChat(e)' name="delete-o" class="delete-icon"/>
                            </template>
                        </van-cell>

                        <!-- 普通显示 -->
                        <van-cell
                                v-else
                                clickable
                                @click="handleClickChat(e)"
                                :title='e.title'
                                icon='chat-o'>
                            <template #extra>
                                <van-icon @click.stop='handleClickEditIcon(e)' name="edit" class="edit-icon"/>
                                <van-icon @click.stop='handleRemoveChat(e)' name="delete-o" class="delete-icon"/>
                            </template>
                        </van-cell>
                    </span>
                </van-cell-group>
            </van-list>
        </van-row>
    </van-popup>
</template>

<script setup>

import {onMounted, reactive, ref, watch, watchPostEffect} from "vue";
import {showConfirmDialog, showFailToast, showToast} from "vant";
import {editChat, listChat, removeAllChat, removeChat} from "@/server/chat/chat";
import {showOptSuccessToast} from "@/utils/common";

// 加载dom元素
const editChatInputDom = ref(null)

// 定义事件
let emit = defineEmits(['updateChat', 'removeChat', 'removeAllChat', 'close', 'clickChat']);

// 父组件传参
const props = defineProps({
    open: Boolean
})

const show = ref(false)

// 会话列表相关数据
const listData = reactive({
    // 是否在初始化时立即请求一次
    immediateCheck: false,
    loading: false,
    error: false,
    finished: false,
    pageNum: 0,
    pageSize: 50,
    list: [],
})

// 会话相关数据
const chatData = reactive({
    id: null,
    title: null
})

// 监听open
watch(() => props.open, async (newValue) => {
    // 打开页面时请求一次
    if (newValue) {
        listData.pageNum = 0
        listData.list = []
        handleListChat()
    }

    show.value = newValue
})
// 监听修改会话标题dom，出现时修改焦点
watchPostEffect(() => {
    if (editChatInputDom.value && editChatInputDom.value.length === 1) {
        editChatInputDom.value[0].focus()
    }
})

// 点击会话
const handleClickChat = (chat) => {
    emit('clickChat', chat);
    show.value = false
}

// 加载会话列表
const handleListChat = () => {
    const condition = {
        pageNum: ++listData.pageNum,
        pageSize: listData.pageSize
    }

    listChat(condition).then(res => {
        listData.list = listData.list.concat(res.rows)
        listData.finished = listData.list.length >= res.total

    }).catch(() => {
        listData.error = true
    }).finally(() => {
        listData.loading = false
    })
}

// 点击修改图标
const handleClickEditIcon = (chat) => {
    listData.list.forEach(i => {
        i.editing = i.id === chat.id

        // 记录需要修改的会话
        if (i.editing) {
            chatData.id = chat.id
            chatData.title = chat.title
            chatData.oldTitle = chat.title
        }
    })
}

// 修改会话
const handleEditChat = () => {
    if (!chatData.title) {
        showFailToast("请输入标题")
        return

        // 修改后与修改前一样
    } else if (chatData.oldTitle === chatData.title) {
        showOptSuccessToast()
        // 重置所有会话的修改状态
        listData.list.forEach(i => {
            i.editing = false
        })
    }

    editChat(chatData).then(() => {
        showOptSuccessToast()
        // 重置所有会话的修改状态，修改对应会话的标题
        listData.list.forEach(i => {
            if (i.id === chatData.id) {
                i.title = chatData.title
                emit("updateChat", chatData)
            }

            i.editing = false
        })
    })
}

// 删除会话
const handleRemoveChat = (chat) => {
    showConfirmDialog({
        title: `您确定要删除该会话吗？`,
        message: `会话标题：[${chat.title}]`,
    }).then(() => {
        // on confirm
        removeChat(chat.id).then(() => {
            showOptSuccessToast()

            // 从列表中删除改会话
            for (let i = 0; i < listData.list.length; i++) {
                const item = listData.list[i]

                if (chat.id === item.id) {
                    listData.list.splice(i, 1)
                    emit("removeChat", chat)
                    break
                }
            }
        })
    }).catch(() => {
    })
}

// 删除所有会话
const handleRemoveChatAll = () => {
    if (listData.list.length === 0) {
        showToast('会话列表为空')
        return
    }

    showConfirmDialog({
        title: `危险操作`,
        message: `您确定要删除所有会话吗？`,
    }).then(() => {
        // on confirm
        removeAllChat().then(() => {
            showOptSuccessToast()

            // 清空列表
            listData.list = []
            emit("removeAllChat")
            show.value = false
        })
    }).catch(() => {
    });
}

</script>

<style scoped lang="less">
.edit-icon {
  margin-left: 7px;
  font-size: 16px;
  line-height: inherit;
}

.delete-icon {
  margin-left: 7px;
  font-size: 16px;
  line-height: inherit;
}
</style>